package main

import (
	"fmt"
	"game/src/common/impl"
	"game/src/conf"
	"io"
	"math/rand"
	"net"
	"strconv"
	"time"
)

/*
	模拟客户端
*/

func main() {

	fmt.Println("Client Test ... start")
	conf.InitConfig()
	// 初始化命令转换
	for i := 0; i < 500; i++ {
		conn, err := net.Dial("tcp", "127.0.0.1:7777")
		if err != nil {
			fmt.Println("client start err, exit!" + err.Error())
			return
		}
		dp := impl.NewDataPack()
		msg, _ := dp.Pack(impl.NewMsgPackage(1, []byte(strconv.Itoa(i))))
		_, err2 := conn.Write(msg)
		if err2 != nil {
			fmt.Println("write error err ", err2)
		}

		go sendMsg2(conn)
		go acceptMsg2(conn)
	}
	for {
		time.Sleep(10 * time.Second)
	}

}

func sendMsg2(conn net.Conn) {

	cmd := &[...]uint32{
		11, 12, 13, 14, 15, 21, 22, 23, 24,
	}

	for {
		index := rand.Intn(9)
		time.Sleep(2 * time.Second)
		msgId := cmd[index]
		dp := impl.NewDataPack()
		param := "test "
		switch msgId {
		case 11:
			param += strconv.Itoa(rand.Intn(20))
		case 22:
			param += strconv.Itoa(rand.Intn(5)) + "  " + strconv.Itoa(rand.Intn(20)) + "  " + strconv.Itoa(rand.Intn(30))
		}
		if msgId == 11 {

		}
		msg, _ := dp.Pack(impl.NewMsgPackage(msgId, []byte(param)))
		_, err := conn.Write(msg)
		if err != nil {
			fmt.Println("write error err ", err)
		}

	}
	//发封包message消息

}

func acceptMsg2(conn net.Conn) {
	dp := impl.NewDataPack()
	for {
		//先读出流中的head部分
		headData := make([]byte, dp.GetHeadLen())
		_, err := io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
		if err != nil {
			fmt.Println("read head error")
			break
		}
		//将headData字节流 拆包到msg中
		msgHead, err := dp.Unpack(headData)
		if err != nil {
			fmt.Println("server unpack err:", err)
			return
		}

		if msgHead.GetDataLen() > 0 {
			//msg 是有data数据的，需要再次读取data数据
			msg := msgHead.(*impl.Message)
			msg.Data = make([]byte, msg.GetDataLen())

			//根据dataLen从io中读取字节流
			_, err := io.ReadFull(conn, msg.Data)
			if err != nil {
				fmt.Println("server unpack data err:", err)
				return
			}
			fmt.Println(string(msg.Data))
		}

	}
}
